package com.hx.er.action.manager.food;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.hx.er.action.base.ErManagerPageAction;
import com.hx.er.bean.base.FoodBean;
import com.hx.er.bean.base.RestraurantBean;
import com.hx.er.common.exception.ErException;
import com.hx.er.common.system.Constants;
import com.hx.er.common.system.ErLanguages;
import com.hx.er.common.system.ErProperties;
import com.hx.er.common.util.FileUtil;
import com.hx.er.common.util.StringUtil;
import com.hx.er.service.manager.IManagerFoodService;

public class ManagerFoodListAction extends ErManagerPageAction {
	// 序列化ID
	private static final long serialVersionUID = 4926512300151605899L;

	// 使用自定义页数，参见父类
	private int dataListLimit = Integer.parseInt(ErProperties.getProperty(Constants.PROPERTY_PIC_PAGE_SIZE));

	// 页面国际化
	public static final String FOOD_PICTURE_EMPTY_MSG = "manager.foodList.message.add.empty.foodPicture";
	public static final String FOOD_NAME_EMPTY_MSG = "manager.foodList.message.add.empty.foodName";
	public static final String FOOD_PRICE_EMPTY_MSG = "manager.foodList.message.add.empty.price";
	public static final String FOOD_PRICE_NUMBER_MSG = "manager.foodList.message.add.number.price";
	public static final String PICTURE_PATH_EMPTY_MSG = "manager.foodList.message.add.empty.picturePath";

	// 食品ID
	private long foodId;
	// 食品对象
	private FoodBean foodBean;
	// 餐厅对象
	private RestraurantBean restBean;
	// 价格
	private String priceStr;
	// 获取上传文件
	private File foodPicture;
	// 获取上传文件名称
	private String foodPictureFileName;
	// 获取上传文件类型
	private String foodPictureContentType;
	// 多语言标签名
	private String labelLang1;
	private String labelLang2;
	private String labelLang3;
	private String labelLang4;
	private String labelLang5;
	// 检索条件中的食品名
	private String foodName1;
	private String foodName2;
	private String foodName3;
	private String foodName4;
	private String foodName5;

	@Autowired
	private IManagerFoodService managerFoodService;

	private List<FoodBean> foodList;

	public String init() {
		// 初始化页面
		try {
			this.initPage();
		} catch (IOException e) {
			this.addActionError(super.getText(OPERATION_FAILURE_MSG));
			return INPUT;
		}

		return SUCCESS;
	}

	public String upload() {
		try {
			if (!this.checkUploadParams()) {
				return INPUT;
			}

			// 循环上传的文件
			InputStream is = null;
			OutputStream os = null;

			if (this.foodBean == null) {
				this.foodBean = new FoodBean();
			}

			try {
				is = new FileInputStream(this.foodPicture);

				// 得到图片保存的位置(根据root来得到图片保存的路径在tomcat下的该工程里)
				String root = request.getServletContext().getRealPath("/");
				this.foodBean.setPicturePath(ErProperties.getProperty(Constants.PROPERTY_PICTURE_ROOT_PATH) + "\\" + this.getNewFileName());
				File destFile = new File(root, this.foodBean.getPicturePath());
				FileUtil.createDir(destFile);

				// 把图片写入到上面设置的路径里
				os = new FileOutputStream(destFile);
				byte[] buffer = new byte[400];
				int length = 0;
				while ((length = is.read(buffer)) > 0) {
					os.write(buffer, 0, length);
				}
			} catch (FileNotFoundException e) {
				throw new ErException(e);
			} catch (IOException e) {
				throw new ErException(e);
			} finally {
				try {
					if (is != null) {
						is.close();
					}
					if (os != null) {
						os.close();
					}
				} catch (IOException e) {
					throw new ErException(e);
				}
			}
		} catch (ErException e) {
			this.addActionError(super.getText(OPERATION_FAILURE_MSG));
			return INPUT;
		} finally {
			try {
				// 初始化页面
				this.initPage();
			} catch (IOException e) {
				// 错误信息
				this.addActionError(super.getText(OPERATION_FAILURE_MSG));
				return INPUT;
			}
		}

		return UPLOAD;
	}

	/**
	 * 保存新菜品
	 * 
	 * @return
	 */
	public String save() {
		try {
			// 属性校验
			if (!this.checkSaveParams()) {
				return INPUT;
			}

			// 读取图片文件
			String root = request.getServletContext().getRealPath("/");
			File pictureFile = new File(root, this.foodBean.getPicturePath());

			// 循环上传的文件
			InputStream is = new FileInputStream(pictureFile);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
			byte[] tempByteArray = new byte[1024];
			while (is.read(tempByteArray) != -1) {
				bos.write(tempByteArray);
			}

			this.foodBean.setPictureFile(bos.toByteArray());
			if (is != null) {
				is.close();
			}

			// 设置食品属性
			this.foodBean.setRestId(super.restId);
			this.foodBean.setCreateUserId(super.userInfoLogin.getUserId());
			this.foodBean.setUpdateUserId(super.userInfoLogin.getUserId());
			this.foodBean.setPrice(Double.parseDouble(this.priceStr));

			// 插入数据库
			this.managerFoodService.insertFoodWithoutId(this.foodBean);

			// 清理页面参数
			this.clearParams();
		} catch (IOException e) {
			// 错误信息
			this.addActionError(super.getText(OPERATION_FAILURE_MSG));
			return INPUT;
		} finally {
			// 初始化页面
			try {
				this.initPage();
			} catch (IOException e) {
				// 错误信息
				this.addActionError(super.getText(OPERATION_FAILURE_MSG));
				return INPUT;
			}
		}

		// 操作成功
		this.addActionMessage(super.getText(OPERATION_SUCCESS_MSG));
		// 页面跳转
		return SAVE;
	}

	public String foodForward() throws IOException {
		// 初始化食品信息，下列属性必须有！
		FoodBean foodBean = new FoodBean();
		foodBean.setFoodId(this.foodId);
		foodBean.setUpdateUserId(super.getUserInfoLogin().getUserId());
		foodBean.setRestId(super.restId);
		
		// 食品前移操作
		boolean result = this.managerFoodService.foodForward(foodBean);
		// 初始化页面
		this.initPage();
		// 页面跳转
		if (result) {
			this.addActionMessage(super.getText(OPERATION_SUCCESS_MSG));
			return SUCCESS;
		} else {
			// 错误信息
			this.addActionError(super.getText(OPERATION_FAILURE_MSG));
			return INPUT;
		}
	}

	public String foodBackward() throws IOException {
		// 初始化食品信息，下列属性必须有！
		FoodBean foodBean = new FoodBean();
		foodBean.setFoodId(this.foodId);
		foodBean.setUpdateUserId(super.getUserInfoLogin().getUserId());
		foodBean.setRestId(super.restId);
		
		// 食品后移操作
		boolean result = this.managerFoodService.foodBackward(foodBean);
		// 初始化页面
		this.initPage();
		// 页面跳转
		if (result) {
			this.addActionMessage(super.getText(OPERATION_SUCCESS_MSG));
			return SUCCESS;
		} else {
			// 错误信息
			this.addActionError(super.getText(OPERATION_FAILURE_MSG));
			return INPUT;
		}
	}

	/**
	 * 获取图片的新名称
	 * 
	 * @return
	 */
	private String getNewFileName() {
		String suffix = this.foodPictureFileName.substring(this.foodPictureFileName.lastIndexOf('.'));
		long time = System.currentTimeMillis();

		return String.valueOf(super.restId) + "\\" + time + suffix;
	}

	/**
	 * 上传图片时检查参数
	 * 
	 * @return
	 */
	private boolean checkUploadParams() {
		// 图片验证
		if (this.foodPicture == null) {
			this.addFieldError("msg.restName", super.getText(FOOD_PICTURE_EMPTY_MSG));
		}

		// 错误信息数量
		int errCount = this.getActionErrors().size() + this.getFieldErrors().size();

		return errCount == 0;
	}

	/**
	 * 保存食品信息时检查参数
	 * 
	 * @return
	 */
	private boolean checkSaveParams() {
		// 菜名校验
		if (StringUtil.isEmpty(this.foodBean.getFoodName1())) {
			this.addFieldError("msg.foodName", super.getText(FOOD_NAME_EMPTY_MSG));
		}

		// 图片验证
		if (StringUtil.isEmpty(this.foodBean.getPicturePath())) {
			if (StringUtil.isEmpty(this.foodPictureFileName)) {
				this.addFieldError("msg.picturePath", super.getText(PICTURE_PATH_EMPTY_MSG));
			} else {
				// 如果文件空间已经加载了文件名，只是文件没有预览上传，则直接上传。
				this.upload();
			}
		}

		// 价格校验
		if (StringUtil.isEmpty(StringUtil.trim(this.priceStr))) {
			this.addFieldError("msg.price", super.getText(FOOD_PRICE_EMPTY_MSG));
		} else if (!StringUtil.isNumeric(StringUtil.trim(this.priceStr))) {
			this.addFieldError("msg.price", super.getText(FOOD_PRICE_NUMBER_MSG));
		}

		// 错误信息数量
		int errCount = this.getActionErrors().size() + this.getFieldErrors().size();

		return errCount == 0;
	}

	/**
	 * 检查文件，如果不存在则重新生成
	 * 
	 * @throws ErException
	 * @throws IOException
	 */
	private void checkPictureFiles() throws IOException {
		// 声明输出流
		OutputStream fos = null;

		// 循环处理列表中所有对象
		for (FoodBean foodBean : this.foodList) {
			String root = request.getServletContext().getRealPath("/");
			File pictureFile = new File(root, foodBean.getPicturePath());

			// 如果所在目录不存在，则先创建
			FileUtil.createDir(pictureFile);

			// 如果文件不存在，则写文件
			if (!pictureFile.exists()) {
				fos = new FileOutputStream(pictureFile);
				fos.write(foodBean.getPictureFile());
				if (fos != null) {
					fos.close();
				}
			}
		}
	}

	private void initPage() throws IOException {
		// 基本检索条件获取
		Map<String, Object> conditions = super.getConditionMap(dataListLimit);
		conditions.put("foodName1", StringUtil.EmptyToNull(this.foodName1));
		conditions.put("foodName2", StringUtil.EmptyToNull(this.foodName2));
		conditions.put("foodName3", StringUtil.EmptyToNull(this.foodName3));
		conditions.put("foodName4", StringUtil.EmptyToNull(this.foodName4));
		conditions.put("foodName5", StringUtil.EmptyToNull(this.foodName5));

		this.foodList = this.managerFoodService.getFoodAliveList(conditions);
		int foodCount = this.managerFoodService.getFoodAliveCount(conditions);

		super.pageCount = (int) Math.ceil(foodCount / (double) super.dataListLimit);

		// 检索餐厅
		this.restBean = this.managerFoodService.getRestById(super.restId);

		// 语言
		if (this.restBean.getLangId1() != 0) {
			this.labelLang1 = ErLanguages.getLocale(this.restBean.getLangId1()).getLanguage().toUpperCase();
		}
		if (this.restBean.getLangId2() != 0) {
			this.labelLang2 = ErLanguages.getLocale(this.restBean.getLangId2()).getLanguage().toUpperCase();
		}
		if (this.restBean.getLangId3() != 0) {
			this.labelLang3 = ErLanguages.getLocale(this.restBean.getLangId3()).getLanguage().toUpperCase();
		}
		if (this.restBean.getLangId4() != 0) {
			this.labelLang4 = ErLanguages.getLocale(this.restBean.getLangId4()).getLanguage().toUpperCase();
		}
		if (this.restBean.getLangId5() != 0) {
			this.labelLang5 = ErLanguages.getLocale(this.restBean.getLangId5()).getLanguage().toUpperCase();
		}

		// 检查图片是否存在，如果不存在，则生成
		this.checkPictureFiles();
	}

	private void clearParams() {
		this.foodBean = new FoodBean();
		this.priceStr = null;
		this.foodPicture = null;
		this.foodPictureFileName = null;
		this.foodPictureContentType = null;
	}

	public List<FoodBean> getFoodList() {
		return foodList;
	}

	public void setFoodList(List<FoodBean> foodList) {
		this.foodList = foodList;
	}

	public File getFoodPicture() {
		return foodPicture;
	}

	public void setFoodPicture(File foodPicture) {
		this.foodPicture = foodPicture;
	}

	public String getFoodPictureFileName() {
		return foodPictureFileName;
	}

	public void setFoodPictureFileName(String foodPictureFileName) {
		this.foodPictureFileName = foodPictureFileName;
	}

	public String getFoodPictureContentType() {
		return foodPictureContentType;
	}

	public void setFoodPictureContentType(String foodPictureContentType) {
		this.foodPictureContentType = foodPictureContentType;
	}

	public FoodBean getFoodBean() {
		return foodBean;
	}

	public void setFoodBean(FoodBean foodBean) {
		this.foodBean = foodBean;
	}

	public String getPriceStr() {
		return priceStr;
	}

	public void setPriceStr(String priceStr) {
		this.priceStr = priceStr;
	}

	public RestraurantBean getRestBean() {
		return restBean;
	}

	public void setRestBean(RestraurantBean restBean) {
		this.restBean = restBean;
	}

	public String getLabelLang1() {
		return labelLang1;
	}

	public String getLabelLang2() {
		return labelLang2;
	}

	public String getLabelLang3() {
		return labelLang3;
	}

	public String getLabelLang4() {
		return labelLang4;
	}

	public String getLabelLang5() {
		return labelLang5;
	}

	public String getFoodName1() {
		return foodName1;
	}

	public void setFoodName1(String foodName1) {
		this.foodName1 = foodName1;
	}

	public String getFoodName2() {
		return foodName2;
	}

	public void setFoodName2(String foodName2) {
		this.foodName2 = foodName2;
	}

	public String getFoodName3() {
		return foodName3;
	}

	public void setFoodName3(String foodName3) {
		this.foodName3 = foodName3;
	}

	public String getFoodName4() {
		return foodName4;
	}

	public void setFoodName4(String foodName4) {
		this.foodName4 = foodName4;
	}

	public String getFoodName5() {
		return foodName5;
	}

	public void setFoodName5(String foodName5) {
		this.foodName5 = foodName5;
	}

	public long getFoodId() {
		return foodId;
	}

	public void setFoodId(long foodId) {
		this.foodId = foodId;
	}

}
